//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by 梁楠 on 16/1/11.
//  Copyright © 2016年 QQ主流框架. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

private let HomeCellId = "HomeCellId"
class HomeTableViewController: BaseTableViewController {

    private lazy var statuses = [Status]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
//        demo()
        
        if !userLogin {
            
            visitroLoginView?.setupUIWithInfo(nil, tipText: "关注一些人，回这里看看有什么惊喜")
            
            return
           
        }
        
        prepareTableView()
        
        loadData { (statuses) -> () in
            guard let list = statuses else {
                
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
            
            self.statuses = list
            self.tableView.reloadData()
        }
    }
    
    private func prepareTableView () {
        
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: HomeCellId)
        
    }
    
    private func loadData (finished : (statuses : [Status]?) -> ()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        guard let token = UserAccountViewModel().token else {
            
            print("用户暂未登陆")
            finished(statuses: nil)
//            SVProgressHUD.showErrorWithStatus("请重新登陆")
            return
        }
        
        let parameters = ["access_token":token]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            guard let dict = result as? [String : AnyObject] else {
                
//                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                print("数据结构错误")
                finished(statuses: nil)
                return
            }
            
            guard let array = dict["statuses"] as? [[String : AnyObject]] else {
                
//                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                print("数据结构错误")
                finished(statuses: nil)
                return
            }
            
            var tempArray = [Status]()
            
            for item in array {
                
                let s = Status(dict: item)
                
                tempArray.append(s)
            }
            
//            self.statuses = tempArray
//            self.tableView.reloadData()
            
            finished(statuses: tempArray)
            
            }) { (_, error) -> Void in
                
//                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                
                print(error)
        }
        
        
    }

//    func demo() {
//        
//        let url = "http://www.weather.com.cn/data/sk/101010100.html"
//        
//        let AFN = AFHTTPSessionManager()
//        
//        //支持反序列化得格式
//        AFN.responseSerializer.acceptableContentTypes?.insert("text/html")
//        
//        SVProgressHUD.showInfoWithStatus("正在加载中.....")
//        
//        AFN.GET(url, parameters: nil, progress: nil, success: { (task, result) -> Void in
//            
//            print(result)
//            SVProgressHUD.dismiss()
//            
//            }) { (task, error) -> Void in
//                print(error)
//                SVProgressHUD.showInfoWithStatus("请检查网络")
//        }
//        
//    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.statuses.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //手写代码 必须手动注册cell
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellId, forIndexPath: indexPath)
        //显示文案
        cell.textLabel?.text = self.statuses[indexPath.row].text
        return cell
    }


}

extension HomeTableViewController {
    
}
